SMS.controller('PlaylistController',
function PlaylistController($scope, $rootScope, utils, globals, model, notifications) {
    $("#LayoutContainer").layout($scope.layoutTwoColumns);

    $rootScope.mediaElement = [];
    $scope.itemType = 'pl';
    $scope.playlists = [];
    $scope.playlistsPublic = [];
    $scope.getPlaylists = function (refresh) {
        if (globals.settings.Debug) { console.log("LOAD PLAYLISTS"); }
        $.ajax({
            url: globals.BaseURL() + '/getPlaylists.view?' + globals.BaseParams(),
            method: 'GET',
            dataType: globals.settings.Protocol,
            timeout: globals.settings.Timeout,
            success: function (data) {
                if (data["sms-response"].playlists.playlist !== undefined) {
                    var items = [];
                    if (data["sms-response"].playlists.playlist.length > 0) {
                        items = data["sms-response"].playlists.playlist;
                    } else {
                        items[0] = data["sms-response"].playlists.playlist;
                    }
                    angular.forEach(items, function (item, key) {
                        if (item.owner == globals.settings.Username) {
                            $scope.playlists.push(item);
                        } else if (item.public) {
                            $scope.playlistsPublic.push(item);
                        }
                    });
                    $scope.$apply();
                }
            }
        });
    }
    $scope.getPlaylist = function (id, action) {
        $rootScope.selectedAutoPlaylist = null;
        $rootScope.selectedPlaylist = id;
        $.ajax({
            url: globals.BaseURL() + '/getPlaylist.view?' + globals.BaseParams() + '&id=' + id,
            method: 'GET',
            dataType: globals.settings.Protocol,
            timeout: globals.settings.Timeout,
            success: function (data) {
                if (typeof data["sms-response"].playlist.entry != 'undefined') {
                    var items = [];
                    var playlist = data["sms-response"].playlist;
                    if (playlist.entry.length > 0) {
                        items = playlist.entry;
                    } else {
                        items[0] = playlist.entry;
                    }
                    if (action == 'add') {
                        angular.forEach(items, function (item, key) {
                            $rootScope.queue.push($scope.mapMediaElement(item));
                        });
                        $scope.$apply();
                        $('body').layout().open('south');
                        notifications.updateMessage(items.length + ' Track(s) Added to Queue', true);
                    } else if (action == 'play') {
                        $rootScope.queue = [];
                        angular.forEach(items, function (item, key) {
                            $rootScope.queue.push($scope.mapMediaElement(item));
                        });
                        var next = $rootScope.queue[0];
                        $scope.$apply(function () {
                            $rootScope.playMediaElement(false, next);
                        });
                        $('body').layout().open('south');
                        notifications.updateMessage(items.length + ' Track(s) Added to Queue', true);
                    } else {
                        $rootScope.mediaElement = [];
                        angular.forEach(items, function (item, key) {
                            $rootScope.mediaElement.push($scope.mapMediaElement(item));
                        });
                        $scope.$apply();
                    }
                } else {
                    $rootScope.mediaElement = [];
                }
            }
        });
    }
    $scope.addMediaElementsToPlaylist = function (data, event) {
        var $this = $(event.target);
        var submenu = $('div#submenu_AddToPlaylist');
        if (submenu.is(":visible")) {
            submenu.fadeOut();
        } else {
            $scope.loadPlaylistsForMenu('submenu_AddToPlaylist');
            //get the position of the placeholder element
            pos = $this.offset();
            width = $this.width();
            height = $this.height();
            //show the menu directly over the placeholder
            submenu.css({ "left": (pos.left) + "px", "top": (pos.top + height + 14) + "px" }).fadeIn(400);
        }
    }
    $scope.playlistMenu = [];
    $scope.loadPlaylistsForMenu = function (menu) {
        var map = {
            create: function (options) {
                var indexElement = options.data;
                return new model.IndexElement(indexElement.id, indexElement.name);
            }
        };
        $.ajax({
            url: globals.BaseURL() + '/getPlaylists.view?' + globals.BaseParams(),
            method: 'GET',
            dataType: globals.settings.Protocol,
            timeout: globals.settings.Timeout,
            success: function (data) {
                var playlists = [];
                if (data["sms-response"].playlists.playlist !== undefined) {
                    if (data["sms-response"].playlists.playlist.length > 0) {
                        playlists = data["sms-response"].playlists.playlist;
                    } else {
                        playlists[0] = data["sms-response"].playlists.playlist;
                    }
                    mapping.fromJS(playlists, map, $scope.playlistMenu);
                }
                /*
                $("<a href=\"#\" childid=\"new\">+ New</a><br />").appendTo("#" + menu);
                $.each(playlists, function (i, playlist) {
                $('<a href=\"#\" id=\"' + playlist.id + '\">' + playlist.name + '</a><br />').appendTo("#" + menu);
                });
                */
            }
        });
    }
    $scope.newPlaylist = function (data, event) {
        var reply = prompt("Choose a name for your new playlist.", "");
        if (reply != 'null' && reply != null && reply != '') {
            $.ajax({
                url: globals.BaseURL() + '/createPlaylist.view?' + globals.BaseParams() + '&name=' + reply,
                method: 'GET',
                dataType: globals.settings.Protocol,
                timeout: globals.settings.Timeout,
                success: function (data) {
                    loadPlaylists(true);
                }
            });
        }
    }
    $scope.deletePlaylist = function () {
        if ($rootScope.selectedPlaylist != null) {
            var id = $rootScope.selectedPlaylist;
            if (utils.confirmDelete('Are you sure you want to delete the selected playlist?')) {
                $.ajax({
                    url: globals.BaseURL() + '/deletePlaylist.view?' + globals.BaseParams() + '&id=' + id,
                    method: 'GET',
                    dataType: globals.settings.Protocol,
                    timeout: globals.settings.Timeout,
                    success: function (data) {
                        $scope.getPlaylists();
                    }
                });
            }
        }
    }
    $scope.savePlaylist = function () {
        if ($rootScope.selectedPlaylist() !== null) {
            var id = $rootScope.selectedPlaylist().id();
            var mediaElements = [];
            ko.utils.arrayForEach($rootScope.mediaElement(), function (item) {
                mediaElements.push(item.id);
            });
            if (mediaElements.length > 0) {
                $.ajax({
                    type: 'GET',
                    url: globals.BaseURL() + '/createPlaylist.view?' + globals.BaseParams(),
                    dataType: globals.settings.Protocol,
                    timeout: globals.settings.Timeout,
                    data: { playlistId: id, mediaElementId: mediaElements },
                    success: function () {
                        $scope.getPlaylist(id);
                        notifications.updateMessage('Playlist Updated!', true);
                    },
                    traditional: true // Fixes POST with an array in JQuery 1.4
                });
            }
        }
    }
    $scope.addToPlaylist = function (data, event) {
        var id = event.currentTarget.id;
        var mediaElements = [];
        ko.utils.arrayForEach($scope.selectedMediaElements(), function (item) {
            mediaElements.push(item.id);
        });
        if (mediaElements.length > 0) {
            $.ajax({
                type: 'GET',
                url: globals.BaseURL() + '/updatePlaylist.view?' + globals.BaseParams(),
                dataType: globals.settings.Protocol,
                timeout: globals.settings.Timeout,
                data: { playlistId: id, mediaElementIdToAdd: mediaElements },
                success: function (data) {
                    $scope.selectedMediaElements(null);
                    updateMessage('Playlist Updated!', true);
                },
                traditional: true // Fixes POST with an array in JQuery 1.4
            });
        }
    }
    $scope.removeSelectedMediaElements = function (data, event) {
        ko.utils.arrayForEach($scope.selectedMediaElements(), function (item) {
            $rootScope.mediaElement.remove(item);
        });
    }
    /* End Playlists */

    /* Launch on Startup */
    $scope.getPlaylists();
    /* End Startup */
});